﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using AMing.Helper.Net40;


namespace AMing.Web.Net40.Extension
{
    /// <summary>
    /// 请在web.config里面添加key为 AES_Password 和 AES_VI_KEY 的配置 
    /// </summary>
    public static class CookieEx
    {
        /// <summary>
        /// AES加密 密码
        /// </summary>
        private static string AES_Password = WebConfigurationManager.AppSettings["AES_Password"];

        private static string AES_VI_KEY = WebConfigurationManager.AppSettings["AES_VI_KEY"];

        /// <summary>
        /// 设置cookie
        /// </summary>
        /// <param name="response"></param>
        /// <param name="name"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        public static void AESCookie_Set(this HttpResponseBase response, string name, string key, string val, int? expiresDay = null)
        {
            HttpCookie cookie = new HttpCookie(name);

            string ase_vi = AESEncrypt.GetIv(16);
            string aes_val = AESEncrypt.Encrypt(val, AES_Password, ase_vi);

            cookie.Values.Add(key, aes_val);
            cookie.Values.Add(AES_VI_KEY, ase_vi);
            if (expiresDay != null && expiresDay > 0)
            {
                cookie.Expires = System.DateTime.Now.AddDays(expiresDay.Value);
            }

            response.AppendCookie(cookie);
        }

        /// <summary>
        /// 获取cookie
        /// </summary>
        /// <param name="response"></param>
        /// <param name="name"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        public static string AESCookie_Get(this HttpRequestBase request, string name, string key)
        {
            if (request.Cookies[name] != null)
            {
                string aes_val = request.Cookies[name].Values[key].ToString();
                string ase_vi = request.Cookies[name].Values[AES_VI_KEY].ToString();
                string val = AESEncrypt.Decrypt(aes_val, AES_Password, ase_vi);

                return val;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 删除cookie
        /// </summary>
        /// <param name="response"></param>
        /// <param name="name"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        public static void Cookie_Delete(this HttpResponseBase response, string name)
        {
            HttpCookie cookie = new HttpCookie(name);
            cookie.Expires = System.DateTime.Now.AddDays(-1);
            response.AppendCookie(cookie);
        }
    }
}
